<template>
	<div class="container-wrap">
		<description logo="iconfont icon-gaojingxinxi" :title="title" :desc="desc" />
		<el-card class="table-wrap" shadow="never">
			<div class="operation mb15">
				<div>
					<el-select  class="width-150 mr10" placeholder="选择告警模块" v-model="alarmModule" clearable>
						<el-option
							v-for="item in moduleOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
					<el-select  class="width-150 mr10" placeholder="选择告警级别" v-model="alarmLevel" clearable>
						<el-option
							v-for="item in levelOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
					<el-select  class="width-150 mr10" placeholder="选择状态" v-model="alarmStatus" clearable>
						<el-option
							v-for="item in infoStatusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
					<el-button type="primary" @click="resetSearch">重置</el-button>
					<el-button type="primary" @click="search">搜索</el-button>
				</div>
				<span>
					<el-button type="primary" :disabled="multipleSelection.length === 0" @click="handleConfirm">确认</el-button>
					<el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleDelAlertMessage">删除</el-button>
					<el-button type="primary" @click="search()">刷新</el-button>
				</span>
			</div>

			<el-table
				ref="tableRef"
				border
				v-loading="tableLoading"
				:data="alarmInfo.data"
				element-loading-text="数据加载中..."
				highlight-current-row
				:row-key="(row:any)=>row.id"
				height="calc(100vh - 455px)"
				@row-click="handleRowClick"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" :reserve-selection="true" width="55" />
				<el-table-column type="index" label="序号" width="80"/>
				<el-table-column prop="level" label="告警级别" show-overflow-tooltip  width="100" >
					<template #default="scope">
						<el-tag
							:type="tagType[scope.row.level].type"
							disable-transitions
						>{{ tagType[scope.row.level].label }}</el-tag
						>
					</template>
				</el-table-column>
				<el-table-column prop="module" label="告警模块" show-overflow-tooltip  width="100">
					<template #default="{row}">
						{{ alarmModuleMap[row.module]  }}
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="产生时间" show-overflow-tooltip  width="180">
					<template #default="{row}">{{row.createTime ? formatDate(new Date(row.createTime),'YYYY-mm-dd HH:MM:SS') : '-' }}</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip  width="180">
					<template #default="{row}">{{row.updateTime ? formatDate(new Date(row.updateTime),'YYYY-mm-dd HH:MM:SS') : '-' }}</template>
				</el-table-column>
				<el-table-column prop="content" label="告警内容" show-overflow-tooltip min-width="100"/>
				<el-table-column prop="times" label="告警次数" show-overflow-tooltip width="100"/>
				<el-table-column prop="status" label="状态" show-overflow-tooltip width="150">
					<template #default="{row}">
						<span :class="{'color-success':row.status,'color-warning':!row.status}">{{ row.status === 1 ? '已读' : '未读' }}</span>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="alarmInfo.params.pageNum"
				v-model:page-size="alarmInfo.params.pageSize"
				@current-change="onHandleCurrentChange"
				@size-change="onHandleSizeChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="alarmInfo.total"
			>
			</el-pagination>
		</el-card>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, computed, getCurrentInstance, onUnmounted } from 'vue';
import Description from '/@/components/description/index.vue';
import { useAlarmApi } from '/@/api/alarm';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { useGlobal } from '/@/stores/global';
import { formatDate } from '/@/utils/formatTime';

export interface AlarmListParams{
	level: string | number | null,
	model: string | null,
	pageNo?: string | number,
	pageSize?: string | number,
	status: string | number | null,
}
interface TagType{
	[key: string | number]: any
}

const title = '告警信息';
const desc = '告警信息是存储系统出现异情况的警告通知，用于帮助管理员及时识别和解决问题';
const alarmModuleMap:{
	[key:string]: string
} = {
	nodes: '节点',
	cluster: '集群',
	devices: '设备',
	storage: '存储'
};
const tableLoading = ref(false);
const alarmModule = ref('');
const alarmLevel = ref('');
const alarmStatus = ref('');

const infoStatusOptions:SelectOptionType[] = [
	{
		label: '未读',
		value: 0
	},
	{
		label: '已读',
		value: 1
	}
];
const levelOptions:SelectOptionType[] = [
	{
		label: '提示',
		value: 0
	},
	{
		label: '一般',
		value: 1
	},
	{
		label: '重要',
		value: 2
	},
	{
		label: '紧急',
		value: 3
	}
];
const moduleOptions:SelectOptionType[] = [
	{
		label: '节点',
		value: 'nodes'
	},
	{
		label: '集群',
		value: 'cluster'
	},
	{
		label: '设备',
		value: 'devices'
	},
	{
		label: '存储',
		value: 'storage'
	}
];
const tagType:TagType = {
	0: {
		type: 'info',
		label: '提示'
	},
	1: {
		type: 'primary',
		label: '一般'
	},
	2: {
		type: 'warning',
		label: '重要'
	},
	3: {
		type: 'danger',
		label: '紧急'
	},
};
let state = reactive({
	alarmInfo: {
		data: [],
		params: {
			pageSize: 10,
			pageNum: 1
		},
		total: 0
	}
});
let { alarmInfo } = toRefs(state);

const getAlarmList = (loading:boolean = false) => {
	tableLoading.value = loading;
	useAlarmApi().getAlertMessageList({
		level: alarmLevel.value === '' ? undefined : alarmLevel.value,
		model: alarmModule.value === '' ? undefined : alarmModule.value,
		pageNo: alarmInfo.value.params.pageNum,
		pageSize: alarmInfo.value.params.pageSize,
		status: alarmStatus.value === '' ? undefined : alarmStatus.value,
	}).then((res) => {
		alarmInfo.value.data = res.data.records;
		alarmInfo.value.total = res.data.total;
	}).finally(() => { tableLoading.value = false; });
};
getAlarmList();

// ws refresh list
const { proxy } = <any>getCurrentInstance();
proxy.mittBus.on('refresh-uncomfirmMessage', () => {
	getAlarmList(true);
});
onUnmounted(() => {
	proxy.mittBus.off('refresh-uncomfirmMessage');
});

const tableRef = ref<InstanceType<typeof ElTable>>();
const search = () => {
	alarmInfo.value.params.pageNum = 1;
	tableRef.value?.clearSelection();
	getAlarmList(true);
};
const resetSearch = () => {
	alarmModule.value = '';
	alarmLevel.value = '';
	alarmStatus.value = '';
};

const handleRowClick = (row:any) => {
	let selected = multipleSelectionId.value.includes(row.id);
	tableRef.value?.toggleRowSelection(row, !selected);
};
const onHandleCurrentChange = () => {
	getAlarmList(true);
};
const onHandleSizeChange = () => {
	getAlarmList(true);
};

// confirm
const storesGlobal = useGlobal();
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val:any) => {
	multipleSelection.value = val;
};
const multipleSelectionId = computed(() => {
	return multipleSelection.value.map(item => item.id);
});
const selectedUrgentMsg = computed(() => multipleSelection.value.filter(item => item.level === 3).length);
const selectedImportantMsg = computed(() => multipleSelection.value.filter(item => item.level === 2).length);
const selectedGeneralMsg = computed(() => multipleSelection.value.filter(item => item.level === 1).length);
const selectedTipMsg = computed(() => multipleSelection.value.filter(item => item.level === 0).length);
const handleConfirm = () => {
	ElMessageBox.confirm(
		`是否确认已读选中的${multipleSelection.value.length}条告警信息？
			</br>
			其中包含  ${msgCountText(selectedTipMsg.value, selectedGeneralMsg.value, selectedImportantMsg.value, selectedUrgentMsg.value)}`,
		'确认告警信息',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			dangerouslyUseHTMLString: true,
			customClass: 'center-message-box'
		}
	).then(() => {
		useAlarmApi().confirmAlertMessage({ ids: multipleSelectionId.value }).then(() => {
			ElMessage.success('确认告警信息成功');
			// fetchAlarmListWithFilter();
			getAlarmList(true);
			tableRef.value?.clearSelection();
			storesGlobal.fetchUncomfirmMessage();
		});
	});
};

// delAlertMessage
const handleDelAlertMessage = () => {
	ElMessageBox.confirm(
		`是否删除选中的 ${multipleSelection.value.length}条 告警信息？
			</br>
			其中包含  ${msgCountText(selectedTipMsg.value, selectedGeneralMsg.value, selectedImportantMsg.value, selectedUrgentMsg.value)}`,
		'删除告警信息',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			dangerouslyUseHTMLString: true,
			customClass: 'center-message-box'
		}
	).then(() => {
		useAlarmApi().delAlertMessage({ ids: multipleSelectionId.value }).then(() => {
			ElMessage.success('删除告警信息成功');
			getAlarmList(true);
			tableRef.value?.clearSelection();
			storesGlobal.fetchUncomfirmMessage();
		});
	});
};

const msgCountText = (tipMsgNum:number, generalMsgNum:number, importantMsgNum:number, urgentMsgNum:number) => {
	const tipMsg = tipMsgNum > 0 ? `${tipMsgNum} 条 提示信息` : '';
	const generalMsg = generalMsgNum > 0 ? `${generalMsgNum} 条 一般信息 ` : '';
	const importantMsg = importantMsgNum > 0 ? `${importantMsgNum} 条 重要信息 ` : '';
	const urgentMsg = urgentMsgNum > 0 ? `${urgentMsgNum} 条 紧急信息` : '';
	return `${tipMsg}${generalMsg}${importantMsg}${urgentMsg}`;
};
</script>